import ctypes
import json
import os
import time
from tkinter import ttk, messagebox

import pyautogui
from ttkthemes import ThemedTk


def is_caps_lock_on():
    # 获取大写锁定键的状态
    return bool(ctypes.windll.user32.GetKeyState(0x14) & 1)


class AccountAutoInputApp:
    def __init__(self, root):
        self.root = root
        self.file_path = self.get_file_path()  # 获取文件路径
        if not os.path.exists(self.file_path):  # 检查文件路径是否存在
            messagebox.showerror("错误", "文件路径不存在，请检查路径！")  # 弹窗提示文件路径不存在
            return
        self.account_info = self.load_accounts(self.file_path)
        self.init_ui()

    def get_file_path(self):
        # 返回固定的文件路径
        return r"D:\Obsidian\obsidianblog\生活\password.sheet.md"

    def load_accounts(self, file_path):
        account_info = {}
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()

            start_index = content.find('[')
            end_index = content.rfind(']') + 1
            json_string = content[start_index:end_index]

            data = json.loads(json_string)

            for i, row in enumerate(data[0]['rows'].values()):
                if isinstance(row, dict) and 'cells' in row and i > 0:
                    account_type = row['cells'].get('0', {}).get('text', '无')
                    account = row['cells'].get('1', {}).get('text', '无')
                    password = row['cells'].get('2', {}).get('text', '无')
                    if account_type != '无' and account != '无' and password != '无':
                        if account_type not in account_info:
                            account_info[account_type] = {"account": account, "password": password}
                        else:
                            print(f"已存在相同类型的账号信息：{account_type}")
        except FileNotFoundError:
            print("文件未找到，请检查路径是否正确")
        except Exception as e:
            print(f"处理文件时发生错误：{e}")

        return account_info

    def init_ui(self):
        self.root.set_theme('arc')  # 使用'arc'主题，你可以替换为其他主题名称
        self.combobox = ttk.Combobox(self.root, values=list(self.account_info.keys()))
        self.combobox.pack(pady=(10, 0))  # 在下拉列表上方增加垂直间距

        input_account_button = ttk.Button(self.root, text="输入账号密码", command=self.input_account_password)
        input_account_button.pack(pady=(10, 10))  # 增加按钮与其他控件之间的垂直间距

        input_password_button = ttk.Button(self.root, text="仅输入密码", command=self.input_password_only)
        input_password_button.pack(pady=(0, 10))  # 增加按钮与其他控件之间的垂直间距

    def apply_styles(self):
        # 应用样式
        style = ttk.Style()
        style.theme_use('clam')  # 使用'clam'主题，根据实际情况选择

        style.configure('TCombobox', foreground='black', background='white')
        style.configure('TButton', font=('Helvetica', 10), background='lightblue')
        style.configure('TLabel', font=('Helvetica', 12), background='lightgrey', foreground='black')

    def input_account_password(self):
        if is_caps_lock_on():
            pyautogui.press('capslock')  # 如果大写锁定开启，则关闭它

        selected_type = self.combobox.get()
        if selected_type:
            account = self.account_info[selected_type]["account"]
            password = self.account_info[selected_type]["password"]
            time.sleep(2)
            pyautogui.hotkey('ctrl', 'a')
            time.sleep(0.5)
            pyautogui.hotkey('alt', 'shift', '0')
            pyautogui.write(account, interval=0.01)
            time.sleep(0.5)
            pyautogui.press('tab')
            pyautogui.write(password, interval=0.01)
            pyautogui.press('enter')

    def input_password_only(self):
        if is_caps_lock_on():
            pyautogui.press('capslock')

        selected_type = self.combobox.get()
        if selected_type:
            password = self.account_info[selected_type]["password"]
            time.sleep(2)
            pyautogui.hotkey('ctrl', 'a')
            time.sleep(0.5)
            pyautogui.hotkey('alt', 'shift', '0')
            pyautogui.write(password, interval=0.01)
            pyautogui.press('enter')


if __name__ == "__main__":
    def center_window(window):
        window.update_idletasks()
        width = window.winfo_width()
        height = window.winfo_height()
        x = (window.winfo_screenwidth() // 2) - (width // 2)
        y = (window.winfo_screenheight() // 2) - (height // 2)
        window.geometry('{}x{}+{}+{}'.format(width, height, x, y))


    root = ThemedTk()
    root.title("密码管理器")
    root.configure(background='white')
    root.geometry("205x150")
    root.resizable(False, False)
    root.attributes('-topmost', 1)
    root.attributes('-toolwindow', 1)
    root.withdraw()
    center_window(root)
    root.deiconify()

    app = AccountAutoInputApp(root)
    root.mainloop()
